//
//  SRBookUnitListViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/7/25.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRBookUnitSelectListViewController.h"

#import "SRBookCatalogueUnitSectionModel.h"
#import "SRBookCatalogueModel.h"

#import "SRBookCatalogueSectionHeaderView.h"
#import "SRBookCatalogueListTableViewCell.h"

#import <MJRefresh/MJRefresh.h>
#import "SRAlbumService.h"
#import "SRCatalogueListTableViewCell.h"

#import "SRClassConstants.h"
#import "SRSchoolClassServices.h"
#import "SRSpeakingTestViewController.h"
#import "FZMCCacheManager.h"

@interface SRBookUnitSelectListViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *sectionItems;//分段数组
@property (assign, nonatomic) NSInteger start;
@property (strong, nonatomic) UIButton *addButton;
@property (strong, nonatomic) SRBookCatalogueModel *selectedModel;

@property (strong, nonatomic) SRBookRootModel *bookModel;

@end

@implementation SRBookUnitSelectListViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupData];
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
        // Do any additional setup after loading the view.
    self.title = @"目录";
    
//    [self setupData];
    [self setupView];
    
//    self.view.backgroundColor =  [UIColor colorWithWhite:0 alpha:0.8];
//    [self setupNavigationBarButtonItem];
   

//    if (!self.startDubbing) {
//        [self queryListData:NO];
//    }else {
	SRBookRootModel *bookModel = [[FZMCCacheManager defaultManager] readBookModelFromDocumentWithBookID:self.bookID];
	self.bookModel = bookModel;
	if (bookModel) {
			//给page添加单元id catalogue_id
		NSArray *catalogueArray = bookModel.catalogues;
		NSArray *pagesArray = bookModel.pages;
		
		for (int i = 0; i < [catalogueArray count]; ++ i) {
			SRBookCatalogueModel *catalogueModel = [catalogueArray objectAtIndex:i];
			for (int j = 0; j < [pagesArray count]; ++ j) {
				SRBookPageModel *pageModel = pagesArray[j];
				NSArray *cataPageIDs = [catalogueModel.page_id splitWith:@","];
				if ([cataPageIDs containsObject:pageModel.pageID]) {
					pageModel.catalogue_id = catalogueModel.catalogue_id;
					
					if (!catalogueModel.page_url) {
						catalogueModel.page_url = pageModel.pageName;
					}
					
				}
			}
		}
		
		if ([self.bookID isEqualToString:@"0"]) {
				//试用教材
			[self.catalogues  addObjectsFromArray:catalogueArray];
		}
	}
    if ([self.bookID isEqualToString:@"0"]) {
        //试用教材
//		[self.catalogues  addObjectsFromArray:catalogueArray];
//		self.bookID = self.bookModel.bookID;
		
        [self updateSectionItems];

        [self.tableView reloadData];
    } else {
        
        [self startProgressHUD];
        [self queryListData:NO];
    }
//        } else {
//            [self showHUDErrorMessage:@"课本解析失败"];
//        }
//
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
}

- (void)readBookFromFile:(NSString *)catalogue_id {
    NSString *catalogueID = catalogue_id;
    
    NSString *currentCatalogueID = catalogueID;
    SRBookCatalogueModel *currentCatalogueModel = nil;
    for (SRBookCatalogueModel *catalogueModel in self.bookModel.catalogues) {
        if ([catalogueModel.catalogue_id isEqualToString:currentCatalogueID]) {
            currentCatalogueModel = catalogueModel;
            break;
        }
    }
    
    NSMutableArray *trackArray = [@[] mutableCopy];
    for (int j = 0; j < [self.bookModel.pages count]; ++ j) {
        SRBookPageModel *pageModel = self.bookModel.pages[j];
        if ([pageModel.catalogue_id isEqualToString:currentCatalogueID] && [pageModel.tracks count] > 0){
            [trackArray addObjectsFromArray:pageModel.tracks];
        }
    }
    
    SRSpeakingTestViewController *vc = [[SRSpeakingTestViewController alloc] init];
    vc.items = trackArray;//self.currentPageModel.tracks;
    vc.catalogueModel = currentCatalogueModel;
    vc.bookID = self.bookID;
    vc.bookName = self.bookModel.name;
//    vc.groupID = self.currentClassModel.identifiter;
//    vc.taskID = workModel.task_id;
    [self.navigationController pushViewController:vc animated:YES];

}


#pragma mark - init

- (void)setupData {
    self.start = 0;
    
    self.sectionItems = [@[] mutableCopy];
    self.catalogues = [@[] mutableCopy];

}

- (void)updateSectionItems {
    [self.sectionItems removeAllObjects];
    
    if (self.catalogues && [self.catalogues count] > 0) {
        NSString *lastUint = nil;
        SRBookCatalogueUnitSectionModel *sectionModel = nil;
        for (int i = 0; i < [self.catalogues count]; ++ i) {
            SRBookCatalogueModel *item = [self.catalogues objectAtIndex:i];
                //            NSLog(@"sort Item Unit:%@", item.unit);
            if (!sectionModel || !lastUint || ![lastUint isEqualToString:item.unit]) {
                lastUint = item.unit;
                if (sectionModel) {
                    [self.sectionItems addObject:sectionModel];
                }
                sectionModel = [[SRBookCatalogueUnitSectionModel alloc] init];
                sectionModel.unit = item.unit;
                [sectionModel.catalogueLists addObject:item];
            } else {
                [sectionModel.catalogueLists addObject:item];
            }
            
            if (i == ([self.catalogues count] - 1) && sectionModel) {
                    //最后一个
                [self.sectionItems addObject:sectionModel];
            }
        }
    }
}


- (void)setupNavigationBarButtonItem {
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"目录";
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.font = [FZStyleSheet currentStyleSheet].fontOfH2;
    
    [self.view addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(20);
        make.height.mas_equalTo(44);
        make.centerX.equalTo(self.view);
    }];
    
    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightButton setTitle:@"关闭" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [rightButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    rightButton.titleLabel.font = [FZStyleSheet currentStyleSheet].fontOfH2;
    [rightButton addTarget: self action: @selector(onCloseButton:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:rightButton];
    
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(20);
        make.trailing.equalTo(self.view).offset(-20);
        make.width.height.mas_equalTo(44);
    }];
    
        //    UIBarButtonItem *rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        //    [self setRightBarButtonItem:rightBarItem];
}
- (void)setupView {
    
        //    WEAKSELF
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 140;
    [self.tableView registerClass:[SRBookCatalogueSectionHeaderView class] forHeaderFooterViewReuseIdentifier:kSRBookCatalogueSectionHeaderView];
    
    [self.tableView registerNib:[UINib nibWithNibName:kSRCatalogueListTableViewCell bundle:nil] forCellReuseIdentifier:kSRCatalogueListTableViewCell];
    
    [self.view addSubview:self.tableView];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.separatorColor = css.color_4;
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0 , 0);
    self.tableView.tableFooterView = [[UIView alloc] init];
    
    
    self.addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.addButton setBackgroundImage:[UIImage imageWithColor:css.color_7] forState:UIControlStateNormal];
    [self.addButton setBackgroundImage:[UIImage imageWithColor:css.colorOfSeperatorColor] forState:UIControlStateDisabled];
    
    [self.addButton setTitleColor:css.color_4 forState:UIControlStateNormal];
    self.addButton.titleLabel.font = css.fontOfH5;
    [self.view addSubview:self.addButton];
    
    [self.addButton setTitle:@"确认添加" forState:UIControlStateNormal];
    [self.addButton addTarget:self action:@selector(onAddButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    if (self.startDubbing) {
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(0);
            make.leading.trailing.equalTo(self.view);
            make.bottom.equalTo(self.view);
        }];
        self.addButton.hidden = YES;
        
    } else {
        [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.equalTo(self.view);
            make.bottom.equalTo(self.view.mas_bottom);
            make.height.mas_equalTo(50);
        }];

        
        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view).offset(0);
            make.leading.trailing.equalTo(self.view);
            make.bottom.equalTo(self.addButton.mas_top);
        }];
        
        
        WEAKSELF
        [self.tableView addLegendFooterWithRefreshingBlock:^{
            [weakSelf queryListData:NO];
        }];
    }
    [self.addButton setEnabled:NO];

    self.tableView.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = css.color_2;
    
   
}

#pragma mark - QueryData 

- (void)queryListData:(BOOL)isRefresh{
    WEAKSELF
    [SRAlbumService queryCatalogueWithBookID:self.bookID start:self.start successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        
        [weakSelf stopProgressHUD];
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess) {
            NSArray *addItems = responseDataObject;
            if ([addItems isKindOfClass:[NSArray class]]) {
                NSInteger itemCount = [addItems count];
                if (isRefresh) {
                    weakSelf.start = itemCount;
                    [weakSelf.catalogues removeAllObjects];
                    
                } else {
                    weakSelf.start += itemCount;
                }
                
                [weakSelf.catalogues addObjectsFromArray:addItems];
                
                if ([weakSelf.catalogues count] > 0) {
                    [weakSelf hideLoadingView];
                } else {
                    [weakSelf emptyLoadingViewWithTitle:nil];
                }
                
                [weakSelf updateSectionItems];
                
                [weakSelf.tableView reloadData];
                
            } else {
                [weakSelf emptyLoadingViewWithTitle:nil];
            }
            
        } else {
            [weakSelf failedLoadingViewWithTitle:message];
        }
    } failBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf.tableView.header endRefreshing];
        [weakSelf.tableView.footer endRefreshing];
        
        if ([weakSelf.catalogues count] > 0) {
            [weakSelf hideLoadingView];
        } else {
            [weakSelf failedLoadingViewWithTitle:nil];
        }
        [weakSelf showHUDError];
    }];
}

#pragma mark - Event

- (void)onCloseButton:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)onAddButtonAction:(id)sender {
    WEAKSELF
    
    [self startProgressHUD];
    
    [SRSchoolClassServices addTaskGroupID:self.groupID bookID:self.selectedModel.book_id catalogueID:self.selectedModel.catalogue_id successBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
        if (statusCode == kFZRequestStatusCodeSuccess) {
            [weakSelf showHUDHintWithText:@"添加成功"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:kSRAddTaskDidSuccessNotification object:nil];
            [weakSelf performSelector:@selector(backToHomework) withObject:nil afterDelay:1];
        } else {
            [weakSelf showHUDHintWithText:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
        [weakSelf stopProgressHUD];
        [weakSelf showHUDError];
    }];
    
}

- (void)backToHomework {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)updateNextButtonTitle {
    NSArray *selectedItems = self.tableView.indexPathsForSelectedRows;
    
    if (selectedItems && [selectedItems count] > 0) {
        [self.addButton setEnabled:YES];
        NSString *title = [NSString stringWithFormat:@"确认添加（%lu）", [selectedItems count]];
        [self.addButton setTitle:title forState:UIControlStateNormal];
        
    } else {
        [self.addButton setEnabled:NO];
        NSString *title = [NSString stringWithFormat:@"确认添加"];
        [self.addButton setTitle:title forState:UIControlStateNormal];
    }
}


#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.sectionItems count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section >= [self.sectionItems count]) {
        return 0;
    }
    
    SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[section];
    
    if (sectionModel.catalogueLists) {
        return [sectionModel.catalogueLists count];
    }
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SRCatalogueListTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kSRCatalogueListTableViewCell forIndexPath:indexPath];
    
    if (indexPath.section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[indexPath.section];
        SRBookCatalogueModel *model = nil;
        
        if ([sectionModel.catalogueLists count] > indexPath.row) {
            model = sectionModel.catalogueLists [indexPath.row];
//            cell.titleLabel.text = model.title;
//            cell.pageLabel.text = [NSString stringWithFormat:@"第%d页", (int)[model.page integerValue]];
            [cell updateCellInfo:model];
            if ([self.bookID isEqualToString:@"0"]) {
                
                UIImage *pageImage = [FZMCCacheManager pageImageWithName:model.page_url bookID:self.bookID];
                
                cell.iconImageView.image = pageImage;
                
            }
            if (self.selectedModel && [self.selectedModel.catalogue_id longLongValue] == [model.catalogue_id longLongValue]) {
                cell.isSelectedStatus = YES;
            } else {
                cell.isSelectedStatus = NO;
            }
        }
        
        if (self.startDubbing) {
            cell.isEditStatus = NO;
        }
    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
        //若没有数据的段，需要隐藏头部高度
    CGFloat defaultHeight = 15;
    if (section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[section];
        if ([sectionModel.catalogueLists count] > 0) {
            return defaultHeight;
        }
    }
    return 0.001;//需要隐藏
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
        //    CGFloat defaultHeight = 50;
    return 10;//需要隐藏
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[section];
        if ([sectionModel.catalogueLists count] > 0) {
            SRBookCatalogueSectionHeaderView *sectionHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kSRBookCatalogueSectionHeaderView];
            sectionHeaderView.leftViewHidden = YES;
            sectionHeaderView.backgroundView.backgroundColor = [FZStyleSheet currentStyleSheet].color_2;
            
            sectionHeaderView.titleLabel.text = [NSString stringWithFormat:@"%@", sectionModel.unit];
            
            return sectionHeaderView;
        }
    }
    
    return nil;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return nil;
}

#pragma mark - UITableViewDelegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section < [self.sectionItems count]) {
        SRBookCatalogueUnitSectionModel *sectionModel = self.sectionItems[indexPath.section];
        if ([sectionModel.catalogueLists count] > indexPath.row) {
            SRBookCatalogueModel *model = sectionModel.catalogueLists[indexPath.row];
            self.selectedModel = model;
            
            if (self.startDubbing) {
                [self readBookFromFile:model.catalogue_id];
                
            } else {
            
                [self.addButton setEnabled:YES];
                [self.tableView reloadData];
            }
//            [self dismissViewControllerAnimated:YES completion:^{
//                if (self.didSelectedCatalogueBlock) {
//                    self.didSelectedCatalogueBlock(model);
//                }
//            }];
            
        }
    }
}


@end

